package com.grm.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * desc: 全局线程池配置类
 *
 * @author gaorimao
 * @since 2023-10-28-17:48
 */
@Configuration
@EnableAsync // 开启支持异步调用
public class ThreadPoolConfig {
    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数,默认为5
        threadPoolTaskExecutor.setCorePoolSize(5);
        // 最大线程数,默认为Integer.MAX_VALUE
        threadPoolTaskExecutor.setMaxPoolSize(20);
        // 队列最大长度,一般需要设置值>=notifyScheduledMainExecutor.maxNum;默认为Integer.MAX_VALUE
        threadPoolTaskExecutor.setQueueCapacity(1000);
        // 线程池维护线程所允许的空闲时间，默认为60s
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        /*
            线程池对拒绝任务（无线程可用）的处理策略
            AbortPolicy:直接抛出java.util.concurrent.RejectedExecutionException异常
            CallerRunsPolicy:主线程直接执行该任务，执行完之后尝试添加下一个任务到线程池中，可以有效降低向线程池内添加任务的速度
            DiscardOldestPolicy:抛弃旧的任务、暂不支持；会导致被丢弃的任务无法再次被执行
            DiscardPolicy:抛弃当前任务、暂不支持；会导致被丢弃的任务无法再次被执行
         */
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待任务在关机时完成--表明等待所有线程执行完
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间(默认为0,此时立即停止),并没等待xx秒后强制停止
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60 * 5);
        //创建线程或线程池时请指定有意义的线程名称，方便出错时回溯
        threadPoolTaskExecutor.setThreadNamePrefix("MyThreadPool-");
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
